import { all } from '@/services/system/permission';
import { ModalForm, ProFormSelect, ProFormText } from '@ant-design/pro-components';
import { FormattedMessage, useIntl } from '@umijs/max';
import { Form } from 'antd';
import React from 'react';

export type UpdateFormProps = {
  onSubmit: (values: SYSTEM.Role) => Promise<void>;
  editModalOpen: boolean;
  setEditModalOpen: (open: boolean) => Promise<void>;
  values: Partial<SYSTEM.Role>;
};

const UpdateForm: React.FC<UpdateFormProps> = (props) => {
  const [form] = Form.useForm<{ name: string; company: string }>();
  const intl = useIntl();
  return (
    <ModalForm<SYSTEM.Role>
      title={props.values.id ? '修改角色' : '新建角色'}
      open={props.editModalOpen}
      onOpenChange={(visible: boolean) => {
        props.setEditModalOpen(visible);
      }}
      form={form}
      onFinish={(formData: SYSTEM.Role) => {
        return props.onSubmit({
          ...props.values,
          name: formData.name,
          permissionIds: formData.permissionIds,
        });
      }}
      width={400}
      modalProps={{ destroyOnClose: true }}
    >
      <ProFormText
        name="name"
        label={intl.formatMessage({
          id: 'pages.user.role.name',
          defaultMessage: 'Role Name',
        })}
        initialValue={props.values.name}
        rules={[
          {
            required: true,
            message: (
              <FormattedMessage
                id="pages.user.role.name.rules"
                defaultMessage="role name not null"
              />
            ),
          },
        ]}
      />
      <ProFormSelect
        name="permissionIds"
        mode="multiple"
        label={intl.formatMessage({
          id: 'pages.user.permission',
          defaultMessage: 'Permission',
        })}
        initialValue={props.values.permissionIds}
        placeholder="请选择权限"
        request={async () => {
          let res = await all();
          let permissions: any[] = [];
          res.data.forEach((item: SYSTEM.Permission) => {
            permissions.push({
              label: item.name,
              value: item.id,
            });
          });
          return permissions;
        }}
      />
    </ModalForm>
  );
};

export default UpdateForm;
